{% extends 'preheat/base.html' %}

{% block title %}请求地址管理 - CDN预热平台{% endblock %}

{% block page_title %}请求地址列表{% endblock %}

{% block content %}
{% csrf_token %}
<div class="mb-4 d-flex justify-content-between align-items-center">
    <a href="{% url 'preheat:request_url_create' %}" class="btn btn-primary">添加请求地址</a>
    
    <!-- CDN域名筛选下拉框 -->
    <div class="ml-auto">
        <form method="get" action="{% url 'preheat:request_url_list' %}" class="form-inline">
            <div class="form-group mr-2">
                <label for="cdn_domain" class="mr-2">筛选域名:</label>
                <select id="cdn_domain" name="cdn_domain" class="form-control" onchange="this.form.submit()">
                    <option value="">全部域名</option>
                    {% for domain in cdn_domains %}
                    <option value="{{ domain.id }}" {% if selected_domain == domain.id|stringformat:"s" %}selected{% endif %}>
                        {{ domain.domain }} ({{ domain.get_vendor_display }})
                    </option>
                    {% endfor %}
                </select>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3>请求地址清单</h3>
    </div>
    <div class="card-body">
        {% if urls %}
        <div class="mb-3">
            <button id="batchDeleteBtn" class="btn btn-danger" disabled>批量删除</button>
        </div>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll"></th>
                        <th>完整URL</th>
                        <th>请求地址</th>
                        <th>关联CDN域名</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for url in urls %}
                    <tr>
                        <td><input type="checkbox" class="url-checkbox" value="{{ url.id }}"></td>
                        <td>{{ url.cdn_domain.domain }}{{ url.url }}</td>
                        <td>{{ url.url }}</td>
                        <td>{{ url.cdn_domain.domain }}</td>
                        <td>{{ url.created_time|date:'Y-m-d H:i:s' }}</td>
                        <td>
                            <a href="{% url 'preheat:request_url_delete' url.id %}" class="btn btn-danger btn-sm" onclick="return confirm('确定要删除该请求地址吗？')">删除</a>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <p class="text-center text-muted">暂无请求地址数据，请点击"添加请求地址"按钮添加地址。</p>
        {% endif %}
    </div>
</div>

<script>
// 全选功能
const selectAllCheckbox = document.getElementById('selectAll');
const urlCheckboxes = document.querySelectorAll('.url-checkbox');
const batchDeleteBtn = document.getElementById('batchDeleteBtn');

// 全选/取消全选
selectAllCheckbox.addEventListener('change', function() {
    const isChecked = this.checked;
    urlCheckboxes.forEach(checkbox => {
        checkbox.checked = isChecked;
    });
    updateBatchDeleteButton();
});

// 单个复选框变更时更新批量删除按钮状态
urlCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        updateBatchDeleteButton();
        // 检查是否所有复选框都被选中
        const allChecked = Array.from(urlCheckboxes).every(cb => cb.checked);
        selectAllCheckbox.checked = allChecked;
    });
});

// 更新批量删除按钮状态
function updateBatchDeleteButton() {
    const checkedBoxes = document.querySelectorAll('.url-checkbox:checked');
    batchDeleteBtn.disabled = checkedBoxes.length === 0;
}

// 批量删除功能
batchDeleteBtn.addEventListener('click', function() {
    const selectedIds = Array.from(document.querySelectorAll('.url-checkbox:checked'))
        .map(checkbox => checkbox.value);
    
    if (selectedIds.length === 0) {
        alert('请至少选择一个请求地址进行删除');
        return;
    }
    
    if (confirm(`确定要删除选中的 ${selectedIds.length} 个请求地址吗？`)) {
        // 使用AJAX提交表单
        const csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
        const deleteUrl = '{% url 'preheat:request_url_batch_delete' %}';
        
        console.log('准备提交AJAX请求到:', deleteUrl);
        console.log('选中的ID:', selectedIds);
        
        // 构建表单数据
        const formData = new FormData();
        formData.append('csrfmiddlewaretoken', csrfToken);
        selectedIds.forEach(id => {
            formData.append('selected_ids', id);
        });
        
        // 发送AJAX请求
        fetch(deleteUrl, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        })
        .then(response => {
            console.log('服务器响应状态:', response.status);
            if (response.ok) {
                // 刷新页面以更新列表
                window.location.reload();
            } else {
                alert('删除操作失败，请重试');
            }
        })
        .catch(error => {
            console.error('AJAX请求错误:', error);
            alert('删除操作发生错误，请重试');
        });
    }
});
</script>
{% endblock %}